package cn.edu.hcnu.controller;

import cn.edu.hcnu.domain.User;
import cn.edu.hcnu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.LinkedList;
import java.util.List;

/**
 * @ClassName ThymeleafController
 * @Description TODO
 * @Author liang
 * @Date 2023/6/18 20:25
 * @Version 1.0
 **/

@Controller
@RequestMapping("/user")
public class ThymeleafController {


    @Autowired
    UserService userService;


    @GetMapping("/insertPage")
    public String addStudent() {
        return "insertPage";
    }

    @PostMapping("/insert")
    public String insert(@ModelAttribute User user) {
        userService.addUser(user);
        return "redirect:/user/userList";
    }

    @PostMapping(value = "/update")
    public String updateStudent(@ModelAttribute User user) {
//        studentService.updateStudent(student);
        userService.updateUser(user);
        return "redirect:/user/userList";
    }

    @GetMapping("/updatePage/{id}")
    public String updatePage(Model model, @PathVariable int id) {
        LinkedList<User> users = new LinkedList<>();
        users.add(userService.getUserById(id));
        model.addAttribute("users", users);
        return "updatePage";
    }

    @GetMapping("/delete/{id}")
    public String deleteStudent(@PathVariable("id") Integer id) {
        userService.deleteUser(id);
        return "redirect:/user/userList";
    }

    @GetMapping("/userList")
    public String display(Model model) {
        List<User> userList = userService.getAll();
        model.addAttribute("userList", userList);
        return "userList";
    }

    @RequestMapping("/find")
    public String userFind(Model model, String name) {
        List<User> userList = userService.findByName(name);
        model.addAttribute("userList", userList);
        return "userList";
    }

}
